import { constantRoutes } from "@/router";
import { generatorDynamicRouter } from "@/router/generatorDynamicRouter";
import { RouteRecordRaw } from "vue-router";

/**
 * 异步查询路由.
 */
export const useAsyncRouteStore = defineStore("app-async-route", () => {
  /**
   * 当前用户的路由.
   */
  const currentUserRouters = ref(constantRoutes);

  /**
   * 设置当前用户的路由
   * @param routers 基础路由外的路由
   */
  const setCurrentUserRouters = (routers: Array<RouteRecordRaw>) => {
    currentUserRouters.value = constantRoutes.concat(routers);
  };

  /**
   * 初始化路由.
   */
  const generateRoutes = async () => {
    try {
      const accessedRouters = await generatorDynamicRouter();
      setCurrentUserRouters(accessedRouters);
      return toRaw(accessedRouters);
    } catch (e) {
      console.log(e);
      throw e;
    }
  };

  return {
    generateRoutes,
  };
});

export const useAsyncRouteStoreOutSetup = () => {
  return useAsyncRouteStore();
};
